using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Data;
using System.Text;

using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Types.Database;
using CdcSoftware.Pivotal.Engine.Types.DataTemplates;
using CdcSoftware.Pivotal.Engine.Types.Localization;
using CdcSoftware.Pivotal.Engine.Types.ServerTasks;

using CdcSoftware.Pivotal.Applications.Core.Server;
using CdcSoftware.Pivotal.Applications.Core.Server.InteractionServices;
using CdcSoftware.Pivotal.Applications.Core.Common;
using System.Collections.Generic;
using System.Linq;

namespace Pcm.Retail.Server.FormTasks
{
    /// <summary>
    /// The Form server task class to undertake some specfic business tasks for a business object
    /// associated with a specified form. It will call service server task to share business
    /// functionality that are not directly related to a form.
    /// </summary>
    /// <history>
    /// #Revision   Date            Author      Description
    /// 6.0.8.1     2011-05-27      DS          Initial version for Retail.
    /// </history>
    public class RE_Staff : AbstractDataTemplateServerTask
    {
        #region Private fields
        static Id originalPurchaseProfID = null;
        #endregion
            
        #region DataTemplateServerTask methods

        /// <summary>
        /// On load of form data
        /// </summary>
        /// <param name="template">DataTemplate object.</param>
        /// <param name="rowId">Record Id of the current business object.</param>
        /// <param name="parameters">ParameterList containing transition point parameter.</param>
        /// <returns>DataSet instance containing the form data that the business object is bound to.</returns>
        /// #Revision   Date        Author  Description
        /// 6.0.9.5     05/03/2010  BR      Initial Version
        /// </history>
        protected override DataSet LoadData(DataTemplate template, Id rowId, ParameterList parameters)
        {
            try
            {
                // Passes the transition point parameter to the TransitionPointParameter instance.
                this.TransitionPointParameter.ParameterList = parameters;
                
                // Load the data.
                DataSet dataSet = SystemServer.DataService.LoadDataDirect(template, rowId, parameters);
                DataRow primaryDataRow = dataSet.Tables[template.PrimaryDataSection.Name].Rows[0];

                //BR: DataRowVersion wont work on STs
                originalPurchaseProfID = Id.Create(primaryDataRow["Staff_Purchase_Profile_Id"]);
                
                this.TransitionPointParameter.CopyToParameterList(parameters);
                return dataSet;
            }
            catch (Exception exc)
            {
                throw new PivotalApplicationCoreException(exc.Message, exc);
            }
        }

       /// <summary>
       /// On the save of new record
        /// </summary>
        /// <param name="template">DataTemplate object.</param>
        /// <param name="data">DataSet instance containing the form data the business object is bound to.</param>
        /// <param name="parameters">ParameterList containing transition point parameter.</param>
        /// <returns>New record Id for the Business Object the form represents.</returns>
        /// <history>
        /// #Revision   Date        Author  Description
        /// 6.0.9.5     05/03/2010  BR      Initial Version
        /// </history>
        protected override Id AddData(DataTemplate template, DataSet data, ParameterList parameters)
        {
            try
            {
                this.TransitionPointParameter.ParameterList = parameters;

                // Gets primary recordset for the operation in the recordset.
                DataRow primaryDataRow = data.Tables[template.PrimaryDataSection.Name].Rows[0];

                // Now add (save) the data to get the record Id i.e RE_Staff_Id.
                Id recordId = this.SystemServer.DataService.AddDataDirect(template, data, parameters);

                if(recordId!=null)
                {
                    if (primaryDataRow["Staff_Purchase_Profile_Id"] != DBNull.Value)
                    {

                        DataTable staffQuota = this.DefaultDataAccess.GetDataTable("RE_Staff Purchase Profile Quota where Profile is ?", new object[] { primaryDataRow["Staff_Purchase_Profile_Id"] }, "Discount_Condition_Id");
                        if (staffQuota != null)
                        {
                            //Create new secondary records on RE_Staff_Purchase for as many records in the Staff Quota table for a particular disc. condition
                            PopulateStaffPurchase(staffQuota, recordId);
                        }
                    }
                }
                // Copies transition point parameter back to the ParameterList object.
                this.TransitionPointParameter.CopyToParameterList(parameters);
                return recordId;
            }

            catch (Exception exc)
            {
                throw new PivotalApplicationCoreException(exc.Message, exc);
            }
        }

        /// <summary>
        /// Called on the save of an existing record
        /// </summary>
        /// <param name="template">DataTemplate object.</param>
        /// <param name="data">DataSet instance of the form data.</param>
        /// <param name="parameters">ParameterList containing transition point parameter.</param>
        /// <history>
        /// #Revision   Date        Author  Description
        /// 6.0.9.5     05/03/2010  BR      Initial Version
        /// </history>
        protected override void SaveData(DataTemplate template, DataSet data, ParameterList parameters)
        {
            try
            {
                this.TransitionPointParameter.ParameterList = parameters;
                DataRow primaryDataRow = data.Tables[template.PrimaryDataSection.Name].Rows[0];

                if (primaryDataRow["Staff_Purchase_Profile_Id"] != DBNull.Value)
                {
                    if (originalPurchaseProfID != Id.Create(primaryDataRow["Staff_Purchase_Profile_Id"]))
                    {
                        DataTable staffQuota = this.DefaultDataAccess.GetDataTable("RE_Staff Purchase Profile Quota where Profile is ?", new object[] { Id.Create(primaryDataRow["Staff_Purchase_Profile_Id"]) }, "Discount_Condition_Id");

                        if (staffQuota != null && staffQuota.Rows.Count > 0)
                        {
                            foreach (DataRow dQuota in staffQuota.Rows)
                            {
                                DataTable staffPurchase = this.DefaultDataAccess.GetDataTable("RE_Staff Purchase with Staff ?  Discount Condition ? Year ?", new object[] { primaryDataRow["RE_Staff_Id"], dQuota["Discount_Condition_Id"], DateTime.Now.Year }, "Calendar_Year");

                                /*Check if there is row for each RE_Staff_Purchase_Prof_Quota.Discount_Condition_Id row for the Staff_Purchase_Profile_Id selected for the current year.
                                If no rows, then populate the RE_Staff_Purchase table */
                                if (staffPurchase != null && staffPurchase.Rows.Count == 0)
                                    PopulateStaffPurchase(staffQuota, primaryDataRow["RE_Staff_Id"]);
                            }
                        }
                    }
                }

                // Save form data
                this.SystemServer.DataService.SaveDataDirect(template, data, parameters);
                this.TransitionPointParameter.CopyToParameterList(parameters);
            }
            catch (Exception exc)
            {
                throw new PivotalApplicationCoreException(exc.Message, exc);
            }
        }

        #endregion

        #region Public methods

        /// <summary>
        /// Send the system generated pass info through email.
        /// </summary>
        /// <param name="letterExpressName"></param>
        /// <param name="subject"></param>
        /// <param name="recordId"></param>
        [TaskExecute]
        public virtual void ResetPassInfoEmail(string letterExpressName, string subject, Id recordId)
        {
            try
            {
                // Send email by use letter express
                LetterExpressEmail letterExpressEmail = (LetterExpressEmail)base.SystemServer.GetMetaItem<ServerTask>("Core Letter Express Email").CreateInstance();
                letterExpressEmail.LoggingBody = false;
                letterExpressEmail.LoggingEnabled = false;
                letterExpressEmail.SendLetterExpressEmail(letterExpressName, subject, recordId);
            }
            catch (Exception e)
            {                
                throw new PivotalApplicationCoreException(e.Message, e);
            }
        }
        #endregion

        #region Private methods

        /// <summary>
        /// Populates the RE_Staff_Purchase table. Common method.
        /// </summary>
        /// <param name="staffProfileQuota">Datatable for Staff Purchase Profile Quota</param>
        /// <param name="staffId">Staff Id</param>
        /// <history>
        /// #Revision   Date        Author  Description
        /// 6.0.9.5     05/03/2010  BR      Initial Version
        /// </history>
        private void PopulateStaffPurchase(DataTable staffProfileQuota, object staffId)//object discountConditionId)
        {
            try
            {
                List<string> staffPurchaseColumns = new List<string>();

                staffPurchaseColumns.Add("Jan_Qty");
                staffPurchaseColumns.Add("Feb_Qty");
                staffPurchaseColumns.Add("Mar_Qty");
                staffPurchaseColumns.Add("Apr_Qty");
                staffPurchaseColumns.Add("May_Qty");
                staffPurchaseColumns.Add("Jun_Qty");
                staffPurchaseColumns.Add("Jul_Qty");
                staffPurchaseColumns.Add("Aug_Qty");
                staffPurchaseColumns.Add("Sep_Qty");
                staffPurchaseColumns.Add("Oct_Qty");
                staffPurchaseColumns.Add("Nov_Qty");
                staffPurchaseColumns.Add("Dec_Qty");
                staffPurchaseColumns.Add("Calendar_Year");
                staffPurchaseColumns.Add("Discount_Condition_Id");
                staffPurchaseColumns.Add("Staff_Id");

                if (staffProfileQuota.Rows.Count > 0)
                {
                    foreach (DataRow drow in staffProfileQuota.Rows)
                    {
                        DataRow staffPurchaseRow = this.DefaultDataAccess.GetNewDataRow("RE_Staff_Purchase", staffPurchaseColumns.ToArray());
                        foreach (string strColumn in staffPurchaseColumns)
                        {
                            staffPurchaseRow[strColumn] = 0;
                        }
                        staffPurchaseRow["Calendar_Year"] = DateTime.Now.Year;
                        staffPurchaseRow["Discount_Condition_Id"] = drow["Discount_Condition_Id"];
                        staffPurchaseRow["Staff_Id"] = TypeConvert.ToDBValue(Id.Create(staffId)); //Current Staff Id

                        this.DefaultDataAccess.SaveDataRow(staffPurchaseRow);
                    }
                }
            }
            catch (Exception e)
            {
                throw new PivotalApplicationCoreException(e.Message, e);
            }
        }

        #endregion
    }
}
